package Model;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;

/**
 * Class Cwindow
 *
 */
class Cwindow extends JFrame implements KeyListener {

    public Cwindow() 
    {
    }

    public void keyPressed(KeyEvent e) {
    }
    public void keyReleased(KeyEvent e) {
    }
    public void keyTyped(KeyEvent e) {            
    }
}

/**
 * Classe Calculette qui créée le graphisme ainsi que les évènements liés à celle-ci
 * @author Maxou
 */
public class Interface extends JFrame implements ActionListener {

    private JTextField firstName;
    private JTextField lastName;
    private JTextField homeAddress;
    private JTextField companyAddress;
    private JTextField personalMobilePhone;
    private JTextField personalHomePhone;
    private JTextField proMobilePhone;
    private JTextField proOfficePhone;
    private JTextField homePage;
    private JTextField proEmail;
    private JTextField personalEmail;
    private JTextField otherIM;
    private JTextField otherSkype;
    private JTextField group;
    private BufferedImage profilePicture;
    private JLabel labelProfilePicture;
    private String picturePath;
    
    private JLabel labelFirstName;
    private JLabel labelLastName;
    private JLabel labelHomeAddress;
    private JLabel labelCompanyAddress;
    private JLabel labelPersonalMobilePhone;
    private JLabel labelPersonalHomePhone;
    private JLabel labelProMobilePhone;
    private JLabel labelProOfficePhone;
    private JLabel labelHomePage;
    private JLabel labelProEmail;
    private JLabel labelPersonalEmail;
    private JLabel labelOtherIM;
    private JLabel labelOtherSkype;
    private JLabel labelContact;
    private JLabel labelGroup;
    
    private JButton buttonAddContact;
    private JButton buttonSaveContact;
    private JButton buttonDeleteContact;
    
    private JPanel panelGeneral;
    private JPanel panelPhoto;
    private JPanel panelName;
    private JPanel panelPhotoAndName;
    private JPanel panelInfo;
    private JPanel panelAddress;
    //private JPanel panelCompanyAddress;
    private JPanel panelContactButtons;
    private JPanel panelContact;
    private JPanel panelList;
    private JPanel panelListAndButtons;
    private JPanel panelPersonalPhones;
    private JPanel panelProPhones;
    private JPanel panelEmail;
    private JPanel panelOther;
    private JPanel panelGroupAndHomePage;
    
    private JTable table;
    private DefaultTableModel model;
        
    private JScrollPane scrollingContactList;
    
    public ArrayList listOfContacts;
    
    float n;
    int c;
    
    public void loadLabels() {
    	
    	labelFirstName = new JLabel();
        labelLastName = new JLabel();
        labelHomeAddress = new JLabel();
        labelCompanyAddress = new JLabel();
        labelPersonalMobilePhone = new JLabel();
        labelPersonalHomePhone = new JLabel();
        labelProMobilePhone = new JLabel();
        labelProOfficePhone = new JLabel();
        labelHomePage = new JLabel();
        labelProEmail = new JLabel();
        labelPersonalEmail = new JLabel();
        labelOtherIM = new JLabel();
        labelOtherSkype = new JLabel();
        labelGroup = new JLabel();
    }
    
    public void loadTextFields()
    {
    	
    	loadLabels();
    	
    	firstName = new JTextField();
    	lastName = new JTextField();
        homeAddress = new JTextField();
        companyAddress = new JTextField();
        personalMobilePhone= new JTextField();
        personalHomePhone = new JTextField();
        proMobilePhone = new JTextField();
        proOfficePhone = new JTextField();
        homePage = new JTextField();
        proEmail = new JTextField();
        personalEmail = new JTextField();
        otherIM = new JTextField();
        otherSkype = new JTextField();
        group = new JTextField();
        
        picturePath = new String("./images/download.jpeg");
    }

    public void loadButtons() {
    	
    	loadTextFields();
    	
    	Font police = new Font("Times News Roman", Font.BOLD, 20);
        
        buttonAddContact = new JButton();
        buttonAddContact.setFont(police);
        buttonAddContact.setText("Add");
        buttonAddContact.addActionListener(this);
        
        buttonSaveContact = new JButton();
        buttonSaveContact.setFont(police);
        buttonSaveContact.setText("Save");
        buttonSaveContact.addActionListener(this);
        
        buttonDeleteContact = new JButton();
        buttonDeleteContact.setFont(police);
        buttonDeleteContact.setText("Delete");
        buttonDeleteContact.addActionListener(this);
        
    }
    
    public void loadPanels() {
    	
    	loadButtons();
    	
    	panelGeneral = new JPanel();
    	panelPhoto = new JPanel();
    	panelName = new JPanel();
    	panelPhotoAndName = new JPanel();
    	panelInfo = new JPanel();
    	panelContactButtons = new JPanel();
    	panelContact = new JPanel();
    	panelList = new JPanel();
    	panelListAndButtons = new JPanel();
    	panelPersonalPhones = new JPanel();
    	panelProPhones = new JPanel();
    	panelEmail = new JPanel();
    	panelOther = new JPanel();
    	panelGroupAndHomePage = new JPanel();
    	panelAddress = new JPanel();
    	//panelCompanyAddress = new JPanel();
    	
    	panelGeneral.setLayout(new GridLayout(1,2));
    	panelPhoto.setLayout(new GridLayout(1, 1));
    	panelName.setLayout(new GridLayout(4,1));
    	panelPhotoAndName.setLayout(new GridLayout(1,2));
    	panelInfo.setLayout(new GridLayout(0,2));
    	panelContactButtons.setLayout(new GridLayout(1,3));
    	panelContact.setLayout(new GridLayout(0,1));
    	panelList.setLayout(new GridLayout(0,1));
    	panelListAndButtons.setSize(200, 350);
    	panelListAndButtons.setLayout(new GridLayout(0,1));
    	panelPersonalPhones.setLayout(new GridLayout(0,2));
    	panelProPhones.setLayout(new GridLayout(0,2));
    	panelEmail.setLayout(new GridLayout(0,2));
    	panelOther.setLayout(new GridLayout(0,2));
    	panelGroupAndHomePage.setLayout(new GridLayout(0,2));
    	panelAddress.setLayout(new GridLayout(0,2));
    	//panelCompanyAddress.setLayout(new GridLayout(0,2));
    	
    	
    	GridBagConstraints gridBagConstraints = new GridBagConstraints();
    	    	
    	labelPersonalMobilePhone.setText("Perso. Mobile Phone");
    	panelPersonalPhones.add(labelPersonalMobilePhone);
    	panelPersonalPhones.add(personalMobilePhone);
    	labelPersonalHomePhone.setText("Perso. Home Phone");
    	panelPersonalPhones.add(labelPersonalHomePhone);
    	panelPersonalPhones.add(personalHomePhone);
    	labelProMobilePhone.setText("Pro. Mobile Phone");
    	panelProPhones.add(labelProMobilePhone);
    	panelProPhones.add(proMobilePhone);
    	labelProOfficePhone.setText("Pro. Office Phone");
    	panelProPhones.add(labelProOfficePhone);
    	panelProPhones.add(proOfficePhone);
    	
    	labelHomeAddress.setText("Home Address");
    	panelAddress.add(labelHomeAddress);
    	panelAddress.add(homeAddress);
    	labelCompanyAddress.setText("Company Address");
    	panelAddress.add(labelCompanyAddress);
    	panelAddress.add(companyAddress);
    	
    	labelPersonalEmail.setText("Perso. Email");
    	panelEmail.add(labelPersonalEmail);
    	panelEmail.add(personalEmail);
    	labelProEmail.setText("Pro. Email");
    	panelEmail.add(labelProEmail);
    	panelEmail.add(proEmail);
    	
    	labelOtherSkype.setText("Skype ID");
    	panelOther.add(labelOtherSkype);
    	panelOther.add(otherSkype);
    	labelOtherIM.setText("Other (IM)");
    	panelOther.add(labelOtherIM);
    	panelOther.add(otherIM);
    	
    	labelFirstName.setText("First Name");
    	panelName.add(labelFirstName);
    	panelName.add(firstName);
    	labelLastName.setText("Last Name");
    	panelName.add(labelLastName);
    	panelName.add(lastName);
    	
    	labelHomePage.addMouseListener(new MouseListener(){

			@Override
			public void mouseClicked(MouseEvent e) {
				if(Desktop.isDesktopSupported())
				{
					try {
						Desktop.getDesktop().browse(new URI(homePage.getText()));
					} catch (IOException | URISyntaxException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			}

			@Override
			public void mousePressed(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mouseReleased(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mouseEntered(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mouseExited(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
        	
        });
    	
    	labelHomePage.setText("HomePage/WebPage");
    	panelGroupAndHomePage.add(labelHomePage);
    	panelGroupAndHomePage.add(homePage);
    	labelGroup.setText("Group:");
    	panelGroupAndHomePage.add(labelGroup);
    	panelGroupAndHomePage.add(group);
    	
    	try {
			profilePicture = ImageIO.read(new File(picturePath));
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	labelProfilePicture = new JLabel(new ImageIcon(profilePicture));
    	labelProfilePicture.setSize(110, 110);
    	labelProfilePicture.addMouseListener(new MouseListener(){

			@Override
			public void mouseClicked(MouseEvent e) {

    			JFileChooser chooser = new JFileChooser();
    			FileNameExtensionFilter filter = new FileNameExtensionFilter(
    			    "JPG & GIF Images", "jpg", "gif", "jpeg");
    			chooser.setFileFilter(filter);
    			chooser.setVisible(true);
    			int returnVal = chooser.showOpenDialog(labelProfilePicture);
    			if(returnVal == JFileChooser.APPROVE_OPTION) 
    			{
    			   System.out.println("You chose to open this file: " +
    			        chooser.getSelectedFile());
    			   picturePath = chooser.getSelectedFile().toString();
    			   try {
   					profilePicture = ImageIO.read(new File(picturePath));
   					Image profileImage = profilePicture.getScaledInstance(110, 110, Image.SCALE_FAST);
   					ImageIcon profileIcon = new ImageIcon(profileImage);
   					//labelProfilePicture.setSize(110, 110);
   					labelProfilePicture.setIcon(profileIcon);
   				} catch (IOException ioe) {
   					// TODO Auto-generated catch block
   					ioe.printStackTrace();
   				}
    			}
				
			}

			@Override
			public void mousePressed(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mouseReleased(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mouseEntered(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mouseExited(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
    		
    	});
    	
    	panelPhoto.add(labelProfilePicture);
    	
    	panelPhotoAndName.add(panelPhoto);
    	panelPhotoAndName.add(panelName);
    	
    	panelContactButtons.add(buttonAddContact);
    	panelContactButtons.add(buttonSaveContact);
    	panelContactButtons.add(buttonDeleteContact);
    	
    	panelContact.add(panelPhotoAndName);
    	panelContact.add(panelPersonalPhones);
    	panelContact.add(panelProPhones);
    	panelContact.add(panelAddress);
    	//panelContact.add(panelCompanyAddress);
    	panelContact.add(panelEmail);
    	panelContact.add(panelOther);
    	panelContact.add(panelGroupAndHomePage);
    	panelContact.add(panelContactButtons);
    	
    	//panelListAndButtons.add(panelListOrderButtons);
    	contactList listContacts = new contactList();
    	listOfContacts = listContacts.load();
    	scrollingContactList = new JScrollPane();
    	for (int i = 0; i < listOfContacts.size(); i++)
    	{
    		labelContact = new JLabel();
    		Contact contactTest = (Contact) listOfContacts.get(i);
    		labelContact.setText(contactTest.firstName + " " + contactTest.lastName );
    		scrollingContactList.add(labelContact);
    	}
    	
    	String[] header = {"Name", "Group", "Date Added/Last Modified"};
        String[][] data = new String[listOfContacts.size()][3];
        for (int j=0; j<listOfContacts.size(); j++) {
        	labelContact = new JLabel();
    		Contact contactTest = (Contact) listOfContacts.get(j);
            data[j][0] = contactTest.firstName + " " + contactTest.lastName;
            data[j][1] = contactTest.group;
            data[j][2] = contactTest.dateAdded;
        }
        
        model = new DefaultTableModel(data, header);
        table = new JTable(model);
        //table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.getColumnModel().getColumn(0).setPreferredWidth(125);
        table.getColumnModel().getColumn(1).setPreferredWidth(50);
        table.getColumnModel().getColumn(2).setPreferredWidth(225);
        table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
			@Override
			public void valueChanged(ListSelectionEvent e) {
				int selectedRow = table.getSelectedRow();
				if (selectedRow != -1)
					changeContactDisplay((String) table.getValueAt(table.getSelectedRow(), 2));
			}
        });

        try {
            // 1.6+
            table.setAutoCreateRowSorter(true);
        } catch(Exception continuewithNoSort) {
        }
        JScrollPane tableScroll = new JScrollPane(table);
    	
    	JButton test = new JButton();
    	test.setText("Test");
    	panelList.add(test);
    	scrollingContactList.add(panelList);
    	panelListAndButtons.add(tableScroll);
    	//panelListAndButtons.add(scrollingContactList);
    	scrollingContactList.setPreferredSize(new Dimension(250,120));
    	//panelListAndButtons.add(panelList);
    	scrollingContactList.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    	buttonAddContact.setSize(WIDTH, 40);
    	//panelListAndButtons.add(buttonAddContact);
    	
    	panelGeneral.add(panelListAndButtons);
    	panelGeneral.add(panelContact);
    	
    	
    }
    
    public void display() {
    	
    	Cwindow window = new Cwindow();
    	window.setSize(800, 600);
    	window.setTitle("Address Book");
    	
    	loadPanels();
    	
    	window.add(panelGeneral);
    	Font police = new Font("Verdana", Font.BOLD, 12);
    	
    	window.setVisible(true);
    	window.setLocationRelativeTo(null);
        window.setDefaultCloseOperation(EXIT_ON_CLOSE);
    	
    	
    }
    
    public void changeContactDisplay(String dateAdded) {
    	for (int i = 0; i < listOfContacts.size(); i++)
    	{
    		Contact comparingContact = (Contact) listOfContacts.get(i);
    		if(comparingContact.dateAdded == dateAdded)
    		{
    			i = listOfContacts.size()+1;
    			if(!comparingContact.firstName.contentEquals("NULL"))
    			{
    				firstName.setText(comparingContact.firstName);
    			}
    			if(!comparingContact.lastName.contentEquals("NULL"))
    			{
    				lastName.setText(comparingContact.lastName);
    			}
    			if(!comparingContact.homeAddress.contentEquals("NULL"))
    			{
    				homeAddress.setText(comparingContact.homeAddress);
    			}
    			if(!comparingContact.companyAddress.contentEquals("NULL"))
    			{
    				companyAddress.setText(comparingContact.companyAddress);
    			}
    			if(!comparingContact.personalMobilePhone.contentEquals("NULL"))
    			{
    				personalMobilePhone.setText(comparingContact.personalMobilePhone);
    			}
    			if(!comparingContact.personalHomePhone.contentEquals("NULL"))
    			{
    				personalHomePhone.setText(comparingContact.personalHomePhone);
    			}
    			if(!comparingContact.proMobilePhone.contentEquals("NULL"))
    			{
    				proMobilePhone.setText(comparingContact.proMobilePhone);
    			}
    			if(!comparingContact.proOfficePhone.contentEquals("NULL"))
    			{
    				proOfficePhone.setText(comparingContact.proOfficePhone);
    			}
    			if(!comparingContact.homePage.contentEquals("NULL"))
    			{
    				homePage.setText(comparingContact.homePage);
    			}
    			if(!comparingContact.personalEmail.contentEquals("NULL"))
    			{
    				personalEmail.setText(comparingContact.personalEmail);
    			}
    			if(!comparingContact.otherIM.contentEquals("NULL"))
    			{
    				otherIM.setText(comparingContact.otherIM);
    			}
    			if(!comparingContact.otherSkype.contentEquals("NULL"))
    			{
    				otherSkype.setText(comparingContact.otherSkype);
    			}
    			if(!comparingContact.group.contentEquals("NULL"))
    			{
    				group.setText(comparingContact.group);
    			}
    			if(!comparingContact.picturePath.contentEquals("NULL"))
    			{
    				try {
    					profilePicture = ImageIO.read(new File(comparingContact.picturePath));
    					Image profileImage = profilePicture.getScaledInstance(110, 110, Image.SCALE_FAST);
       					ImageIcon profileIcon = new ImageIcon(profileImage);
    					labelProfilePicture.setIcon(profileIcon);
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    				
    			}
    		}
    	}
    }

    /**
     * Fonction actionPerformed qui gère les actions des divers évènements
     * @param e 
     */
    public void actionPerformed(ActionEvent e) {
        
        if (e.getActionCommand().equals("Add")) {
        	firstName.setText("");
        	lastName.setText("");
        	homeAddress.setText("");
        	companyAddress.setText("");
        	personalMobilePhone.setText("");
        	personalHomePhone.setText("");
        	proMobilePhone.setText("");
        	proOfficePhone.setText("");
        	homePage.setText("");
        	proEmail.setText("");
        	personalEmail.setText("");
        	otherIM.setText("");
        	otherSkype.setText("");
        	firstName.setText("");
        	group.setText("");
        	try {
        		picturePath = "./images/download.jpeg";
    			profilePicture = ImageIO.read(new File(picturePath));
				Image profileImage = profilePicture.getScaledInstance(110, 110, Image.SCALE_FAST);
				ImageIcon profileIcon = new ImageIcon(profileImage);
				labelProfilePicture.setIcon(profileIcon);
    		} catch (IOException ioe) {
    			// TODO Auto-generated catch block
    			ioe.printStackTrace();
    		}
        	SwingUtilities.invokeLater(new Runnable() {

				@Override
				public void run() {
					table.getSelectionModel().clearSelection();
				}
        	});
        	
        	//table.clearSelection();
        	
        }

        if (e.getActionCommand().equals("Save")) {
	        	int nullValues = 0;
	        	int selectedRow = table.getSelectedRow();
	        	Contact savingContact = new Contact();
	        	Date d = new Date();
	        	for (int i = 0; i < listOfContacts.size(); i++)
	        	{
	        		Contact comparingContact = (Contact) listOfContacts.get(i);
	        		if(comparingContact.dateAdded == d.toString())
	        		{
	        			try {
							wait(1000);
						} catch (InterruptedException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
	        			i = listOfContacts.size();
	        		}
	        	}
	        	if (firstName.getText().isEmpty())
	        	{
	        		savingContact.firstName = "NULL"; 
	        		nullValues++;
	        	}
	        	else
	        		savingContact.firstName = firstName.getText();
	        	if (lastName.getText().isEmpty())
	        	{
	        		savingContact.lastName = "NULL";
	        		nullValues++;
	        	}
	        	else
	        		savingContact.lastName = lastName.getText();
	        	if (homeAddress.getText().isEmpty())
	        	{
	        		savingContact.homeAddress = "NULL";
	        		nullValues++;
	        	}
	        	else
	        		savingContact.homeAddress = homeAddress.getText();
	        	if (companyAddress.getText().isEmpty())
	        	{
	        		savingContact.companyAddress = "NULL";
	        		nullValues++;
	        	}
	        	else
	        		savingContact.companyAddress = companyAddress.getText();
	        	if (personalMobilePhone.getText().isEmpty())
	        	{
	        		savingContact.personalMobilePhone = "NULL";
	        		nullValues++;
	        	}
	        	else
	        		savingContact.personalMobilePhone = personalMobilePhone.getText();
	        	if (proMobilePhone.getText().isEmpty())
	        	{
	        		savingContact.proMobilePhone = "NULL";
	        		nullValues++;
	        	}
	        	else
	        		savingContact.proMobilePhone = proMobilePhone.getText();
	        	if (personalHomePhone.getText().isEmpty())
	        	{
	        		savingContact.personalHomePhone = "NULL";
	        		nullValues++;
	        	}
	        	else
	        		savingContact.personalHomePhone = personalHomePhone.getText();
	        	if (proOfficePhone.getText().isEmpty())
	        	{
	        		savingContact.proOfficePhone = "NULL";
	        		nullValues++;
	        	}
	        	else
	        		savingContact.proOfficePhone = proOfficePhone.getText();
	        	if (homePage.getText().isEmpty())
	        	{
	        		savingContact.homePage = "NULL";
	        		nullValues++;
	        	}
	        	else
	        		savingContact.homePage = homePage.getText();
	        	if (proEmail.getText().isEmpty())
	        	{
	        		savingContact.proEmail = "NULL";
	        		nullValues++;
	        	}
	        	else
	        		savingContact.proEmail = proEmail.getText();
	        	if (personalEmail.getText().isEmpty())
	        	{
	        		savingContact.personalEmail = "NULL";
	        		nullValues++;
	        	}
	        	else
	        		savingContact.personalEmail = personalEmail.getText();
	        	if (otherIM.getText().isEmpty())
	        	{
	        		savingContact.otherIM = "NULL";
	        		nullValues++;
	        	}
	        	else
	        		savingContact.otherIM = otherIM.getText();
	        	if (otherSkype.getText().isEmpty())
	        	{
	        		savingContact.otherSkype = "NULL";
	        		nullValues++;
	        	}
	        	else
	        		savingContact.otherSkype = otherSkype.getText();
	        	if (group.getText().isEmpty())
	        	{
	        		savingContact.group = "none";
	        	}
	        	else
	        		savingContact.group = group.getText();
	        	
	        	savingContact.picturePath = picturePath;
	        	
	        if (selectedRow == -1)
	        {
	        	if (nullValues < 13)
	        	{
	        		savingContact.saveContact();
	        		model.addRow(new Object[]{(savingContact.firstName + " " + savingContact.lastName), savingContact.group, savingContact.dateAdded});
	        	}
	        }
        	else
        	{
            	System.out.println("modify" + selectedRow);
            	String date = (String) table.getValueAt(selectedRow, 2);
            	savingContact.modify(date);
            	if (selectedRow != -1)
            	{
            		table.clearSelection();
            		model.removeRow(selectedRow);
            		model.addRow(new Object[]{(savingContact.firstName + " " + savingContact.lastName), savingContact.group, savingContact.dateAdded});
            	}
        	}

        }
        if (e.getActionCommand().equals("Delete")) {
        	int selectedRow = table.getSelectedRow();
        	System.out.println("delete" + table.getSelectedRow());
        	String date = (String) table.getValueAt(selectedRow, 2);
        	Contact dummy = new Contact();
        	dummy.delete(date);
            //table.remove(table.getSelectedRow());
        	
        	table.clearSelection();
        	if (selectedRow != -1)
        		model.removeRow(selectedRow);
        	//model.fireTableRowsDeleted(selectedRow, selectedRow);
            //model.removeRow(table.getSelectedRow());
            //model.fireTableDataChanged();

        	
        }

    }
}
